package com.myjoje.service.system;

import com.myjoje.base.BaseService;
import com.myjoje.bean.system.*;
import com.myjoje.bean.UserBean;
import com.myjoje.config.AppCache;
import com.myjoje.config.shiro.ShiroUtil;
import com.myjoje.config.support.DaoSupport;
import com.myjoje.dao.system.MenuDao;
import com.myjoje.dao.system.UserDao;
import com.myjoje.jpa.MenuRoleJpa;
import com.myjoje.jpa.RoleJpa;
import com.myjoje.jpa.UserJpa;
import com.myjoje.util.Message;
import com.sun.xml.internal.messaging.saaj.packaging.mime.util.BEncoderStream;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 用户，角色，以及关系维护
 */
@Service
public class UserService extends BaseService {

    @Autowired
    private RoleJpa roleJpa;

    @Autowired
    private UserJpa userJpa;

    @Autowired
    private UserDao userDao;

    @Autowired
    private MenuService menuService;

    @Autowired
    private DeptService deptService;


    /**
     * 根据身份查找用户
     *
     * @param principal
     * @return
     */
    public UserBean findUserByPrincipal(String principal) {
        return userDao.findUserByPrincipal(principal);
    }

    /**
     * 获取用户列表
     */
    public List<UserBean> getUserList(String roleId, String deptId, String sContent, Integer currentPage, Integer pageSize) {
        Map map = getMap("status", UserBean.STATUS_NORMAL);
        map.put("roleId", roleId);
        map.put("deptId", deptId);
        map.put("sContent", sContent);
        return getUserList(currentPage, pageSize, map);
    }

    /**
     * 获取用户列表
     */
    public List<UserBean> getUserList(Integer currentPage, Integer pageSize, Map params) {
        List<UserBean> list = userDao.get(currentPage, pageSize, params);
        //处理密码和openId
        list = list.stream().map(user -> {
            user.setPassword(null);
            user.setOpenid(null);
            return user;
        }).collect(Collectors.toList());
        return list;
    }

    /**
     * 获取用户数量
     */
    public Long getUserCount(String roleId, String deptId, String sContent) {
        Map map = getMap("status", UserBean.STATUS_NORMAL);
        map.put("roleId", roleId);
        map.put("deptId", deptId);
        map.put("sContent", sContent);
        return getUserCount(map);
    }

    /**
     * 获取用户数量
     */
    public Long getUserCount(Map map) {
        return userDao.getCount(map);
    }


    /**
     * 角色列表
     */
    public List<RoleBean> getRoleList(String name, Integer currentPage, Integer pageSize) {
        Map map = getMap("name", name);
        return userDao.getRoleList(currentPage, pageSize, map);
    }

    /**
     * 角色数量
     */
    public Long getRoleCount(String name) {
        Map map = getMap("name", name);
        return userDao.getRoleCount(map);
    }

    /**
     * 添加或更新用户
     */
    public Message saveOrUpdateUser(UserBean bean) {
        String id = bean.getId();
        if (isEmpty(id)) {
            return addUser(bean);
        } else {
            return updateUser(bean);
        }
    }

    /**
     * 更新用户，用户名不可以修改，电话号码可修改
     */
    public Message updateUser(UserBean bean) {
        String id = bean.getId();
        String phoneNum = bean.getPhoneNum();
        UserBean oldBean = userJpa.getOne(id);
        //用户名不允许修改
        if (!oldBean.getUsername().equals(bean.getUsername())) {
            return Message.error("用户名不允许修改");
        }

        //手机号码允许修改
        if (!oldBean.getPhoneNum().equals(phoneNum)) {
            Long phoneNumCount = userJpa.countByPhoneNumAndStatus(phoneNum, UserBean.STATUS_NORMAL);
            if (phoneNumCount > 0) {
                return Message.error("电话号码已存在");
            }
        }
        bean.setPassword(oldBean.getPassword());
        bean.setOpenid(oldBean.getOpenid());
        bean.setModifyTime(getDateTime());
        bean.setModifyUser(getCurrentUserId());
        userJpa.save(bean);
        return Message.success("更新成功");
    }

    /**
     * 添加用户
     */
    private Message addUser(UserBean bean) {
        //验证用户名
        String username = bean.getUsername();
        if (isEmpty(username)) {
            return Message.error("用户名不能为空");
        }
        Long usernameCount = userJpa.countByUsernameAndStatus(username, UserBean.STATUS_NORMAL);
        if (usernameCount > 0) {
            return Message.error("用户名已存在");
        }
        //验证电话号码
        String phoneNum = bean.getPhoneNum();
        Long phoneNumCount = userJpa.countByPhoneNumAndStatus(phoneNum, UserBean.STATUS_NORMAL);
        if (phoneNumCount > 0) {
            return Message.error("电话号码已存在");
        }
        bean.setStatus(UserBean.STATUS_NORMAL);
        bean.setPassword(ShiroUtil.getMd5("123"));
        bean.setCreateTime(getDateTime());
        bean.setCreateUser(getCurrentUserId());
        userJpa.save(bean);
        return Message.success("保存成功");
    }

    /**
     * 添加或更新角色
     */
    public Message saveOrUpdateRole(RoleBean bean) {
        String id = bean.getId();
        if (isEmpty(id)) {//添加
            return addRole(bean);
        } else {//更新
            return updateRole(bean);
        }
    }

    /**
     * 更新角色
     */
    private Message updateRole(RoleBean bean) {
        String id = bean.getId();
        String name = bean.getName();
        RoleBean oldBean = roleJpa.getOne(id);
        String oldName = oldBean.getName();
        if (name.equals(oldName) && bean.getPriority().equals(oldBean.getPriority())) {
            return Message.error("请修改后提交");
        }
        //角色名称和原来的不同
        if (!name.equals(oldName)) {
            if (roleJpa.countByName(name) > 0) {
                return Message.error("角色名称已经存在");
            }
        }
        bean.setModifyTime(getDateTime());
        bean.setModifyUser(getCurrentUserId());
        roleJpa.save(bean);
        return Message.success("修改成功");
    }

    /**
     * 添加角色
     */
    private Message addRole(RoleBean bean) {
        String name = bean.getName();
        if (isEmpty(name)) {
            return Message.error("角色名称不能为空");
        }
        String code = bean.getCode();
        if (isEmpty(code)) {
            return Message.error("角色编码不能为空");
        }
        String priority = bean.getPriority();
        if (isEmpty(priority)) {
            return Message.error("优先级不能为空");
        }
        Long nameCount = roleJpa.countByName(name);
        if (nameCount > 0) {
            return Message.error("角色名称已经存在");
        }
        Long codeCount = roleJpa.countByCode(code);
        if (codeCount > 0) {
            return Message.error("角色编码已经存在");
        }
        bean.setCreateTime(getDateTime());
        bean.setCreateUser(getCurrentUserId());
        roleJpa.save(bean);
        AppCache.setRole(code, bean.getId());
        return Message.success("保存成功");
    }


    /**
     * 删除用户
     */
    public Object deleteUser(String id) {
        Map map = getMap("status", UserBean.STATUS_DELETE);
        userDao.updateById(id, getCurrentUserId(), map);
        return Message.success("删除成功");
    }

    /**
     * 获取所有角色
     *
     * @return
     */
    public Message getAllRole() {
        List<RoleBean> list = userDao.getRoleList(null, null, null);
//        //超级管理员返回全角色
//        if (ShiroUtil.hasRole(AppCache.getRoleRoot())) {
//            return Message.success("获取成功", list);
//        }
//        list = list.stream().filter(bean -> !bean.getId().equals(AppCache.getRoleRoot()))
//                .collect(Collectors.toList());
        return Message.success("获取成功", list);
    }

    /**
     * 为超级管理添加所有的部门
     */
    public void updateRootDeptIds(String deptIds) {
        userDao.updateRootDeptIds(deptIds);
    }

    /**
     * 根据部门id获取用户数量
     */
    public Long getUserCountByDeptId(String deptId) {
        Map map = getMap("deptId", deptId);
        return userDao.getCount(map);
    }

    /**
     * 移除用户部门
     */
    public Message deleteUserDept(String userId, String removeDeptId) {
        if (isEmpty(removeDeptId)) {
            return Message.error("部门id不能为空");
        }
        Optional<UserBean> optional = userJpa.findById(userId);
        if (optional.isPresent()) {
            UserBean bean = optional.get();
            List<String> list = Arrays.asList(bean.getDeptIds().split(","));
            String deptIds = list.stream().
                    filter(deptId -> !deptId.equals(removeDeptId))
                    .collect(Collectors.joining(","));
            bean.setDeptIds(deptIds);
            bean.setModifyTime(getDateTime());
            bean.setModifyUser(getCurrentUserId());
            userJpa.save(bean);
        }
        return Message.success("移除成功");
    }

    /**
     * 移除用户角色
     */
    public Object deleteUserRole(String userId, String removeRoleId) {
        if (isEmpty(removeRoleId)) {
            return Message.error("角色id不能为空");
        }
        Optional<UserBean> optional = userJpa.findById(userId);
        if (optional.isPresent()) {
            UserBean bean = optional.get();
            List<String> list = Arrays.asList(bean.getRoleIds().split(","));
            String roleIds = list.stream().
                    filter(roleId -> !roleId.equals(removeRoleId))
                    .collect(Collectors.joining(","));
            bean.setRoleIds(roleIds);
            bean.setModifyTime(getDateTime());
            bean.setModifyUser(getCurrentUserId());
            userJpa.save(bean);
        }
        return Message.success("移除成功");
    }

    /**
     * 添加用户部门
     */
    public Message addUserDept(String userId, String deptId) {
        if (isEmpty(deptId)) {
            return Message.error("部门id不能为空");
        }
        Optional<UserBean> optional = userJpa.findById(userId);
        if (optional.isPresent()) {
            UserBean bean = optional.get();
            String deptIds = bean.getDeptIds();
            //部门id为空
            if (isEmpty(deptIds)) {
                bean.setDeptIds(deptId);
            } else {
                //deptIds不包含追加
                if (!deptIds.contains(deptId)) {
                    List<String> list = new ArrayList<>(Arrays.asList(deptIds.split(",")));

                    list.add(deptId);
                    deptIds = list.stream().collect(Collectors.joining(","));
                    bean.setDeptIds(deptIds);
                }
            }
            bean.setModifyTime(getDateTime());
            bean.setModifyUser(getCurrentUserId());
            userJpa.save(bean);
            return Message.success("添加成功");
        }
        return Message.error("用户不存在");
    }

    /**
     * 根据角色获取用户
     */
    public Message getUserByRole(String role) {
        return Message.success("请求成功", getUserListByRole(role));
    }

    public List<UserBean> getUserListByRole(String role) {
        return getUserListByRoleAndDept(role, null);
    }

    public List<UserBean> getUserListByRoleAndDept(String role, String dept) {
        Map map = getMap("deptId", dept);
        map.put("roleId", role);
        if ("2".equals(role)) {
            map.put("roleId", AppCache.getRoleAdmin());
        }
        List<UserBean> list = getUserList(null, null, map);
        return list;
    }


    /**
     * 获取用户菜单
     */
    public Object getUserMenu() {
        //用户的角色
        String roleIds = getCurrentUser().getRoleIds();
        List<MenuBean> list = new ArrayList<>();
        if (isEmpty(roleIds)) {
            return Message.success("请求成功", list);
        } else {
            list = menuService.getMenuByRoleIds(roleIds);
            return Message.success("请求成功", list);
        }

    }

    /**
     * 获取用户部门
     */
    public Object getUserDept() {
        UserBean user = getCurrentUser();
        String deptIds = user.getDeptIds();
        List<DeptBean> list = new ArrayList<>();
        if (isNotEmpty(deptIds)) {
            list = deptService.getDeptByIds(new HashSet<>(Arrays.asList(deptIds.split(","))));
        }
        return Message.success("请求成功", list);
    }
}
